<template>
    <el-row :gutter="40">
        <el-col :span="14">
            <el-card v-loading="loading">
                <template #header>
                    <div class="card-header">
                        <div class="buttons">
                            <div class="mb-4">
                                <el-button type="primary" round @click="addNew">新增</el-button>
                                <el-button type="success" round @click="update">修改</el-button>
                                <el-button type="danger" round @click="handeleDelete">删除</el-button>
                                <el-button type="warning" round @click="toggleSelection()">清空选择</el-button>
                            </div>
                        </div>
                    </div>
                </template>
                <el-table ref="multipleTableRef" :data="tableData" style="width: 100%; height: 400px;"
                    @selection-change="handleSelectionChange" @row-click="handleRowChick">
                    <el-table-column type="selection" width="55" />
                    <el-table-column property="name" label="名称" width="120" />
                    <el-table-column property="dataScope" label="数据权限" width="120" />
                    <el-table-column property="level" label="角色级别" width="120" />
                    <el-table-column property="createTime" label="创建时间" width="240" />
                </el-table>
                <template #footer>
                    <div class="example-pagination-block">
                        <el-pagination layout="prev, pager, next" :default-page-size="pageSize"
                            v-model:current-page="currentPage" :total="totalSize" @current-change="getRoleByPage" />
                    </div>

                </template>
            </el-card>

        </el-col>
        <el-col :span="8">
            <el-card style="max-width: 480px" v-loading="loadingMenu">
                <template #header>
                    <div style="display: flex;">
                        <span style="margin-top: 5px;">菜单授权</span>

                        <el-button type="primary" round @click="save"
                            style="justify-content: flex-end; margin-left: auto;"
                            :disabled="multipleSelection.length != 1">保存</el-button>
                    </div>

                </template>
                <div class="grid-content ep-bg-purple">
                    <el-tree ref="treeRef" style="max-width: 600px" :data="data" show-checkbox node-key="id"
                        :props="defaultProps" />
                </div>
            </el-card>


        </el-col>
    </el-row>

    <!-- 更新员工表单 -->
    <el-drawer v-model="drawer_update" title="修改员工">
        <el-form ref="updateFormRef" style="max-width: 600px" :model="updateForm" :rules="updaterules"
            label-width="auto" class="demo-ruleForm" status-icon>
            <el-form-item label="名称" prop="name">
                <el-input v-model="updateForm.name" />
            </el-form-item>
            <el-form-item label="权限等级" prop="level">
                <el-select v-model="updateForm.level" placeholder="1为最高权限">
                    <el-option label="1" value="1" />
                    <el-option label="2" value="2" />
                </el-select>
            </el-form-item>
            <el-form-item label="数据权限" prop="dataScope">
                <el-select v-model="updateForm.dataScope" placeholder="">
                    <el-option label="全部" value="全部" />
                    <el-option label="本级" value="本级" />
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitUpdateForm(updateFormRef)">
                    提交
                </el-button>
                <el-button @click="resetUpdateForm(updateFormRef)">重置表单</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>

    <!-- 新建员工 -->
    <el-drawer v-model="drawer_new" title="新建员工">
        <el-form ref="newFormRef" style="max-width: 600px" :model="newForm" :rules="newrules" label-width="auto"
            class="demo-ruleForm" status-icon>
            <el-form-item label="名称" prop="name">
                <el-input v-model="newForm.name" />
            </el-form-item>
            <el-form-item label="权限等级" prop="level">
                <el-select v-model="newForm.level" placeholder="1为最高权限">
                    <el-option label="1" value="1" />
                    <el-option label="2" value="2" />
                </el-select>
            </el-form-item>
            <el-form-item label="数据权限" prop="dataScope">
                <el-select v-model="newForm.dataScope" placeholder="">
                    <el-option label="全部" value="全部" />
                    <el-option label="本级" value="本级" />
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitNewForm(newFormRef)">
                    提交
                </el-button>
                <el-button @click="resetNewForm(newFormRef)">重置表单</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>

</template>




<script lang="ts" setup>
import { ref, reactive, nextTick, onBeforeMount } from 'vue'
import { ElTable, ElTree, ElNotification } from 'element-plus'
import { getRoleByPage, updateRoleMenu, updateRole, deleteRole, createRole } from '@/api/role';
import { getMenu } from '@/api/menu';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

interface Role {
    id: string
    name: string
    dataScope: string
    level: string
    menus: Array<object>
    createTime: string
    depts: Array<string>
}

//按钮功能
const drawer_new = ref(false)
const drawer_update = ref(false)

function addNew() {
    drawer_new.value = true;
}

function update() {
    if (multipleSelection.value.length != 1) {
        ElNotification({
            title: "Warning",
            message: "请选择单个角色",
            type: "warning"
        })
    } else {
        drawer_update.value = true;
    }
}

const handeleDelete = async () => {
    if (multipleSelection.value.length <= 0) {
        ElNotification({
            title: "Warning",
            type: "warning",
            message: "请选择删除对象"
        })
        return
    }
    let deleteArray = []
    for (let i of multipleSelection.value) {

        deleteArray.push(i.id)
    }
    loading.value = true;
    const res = await deleteRole(deleteArray);
    if (res.status == "200") {
        getByPage()
        ElNotification({
            title: "Success",
            type: "success",
            message: "删除成功"
        })
    } else {
        ElNotification({
            title: "Error",
            type: "error",
            message: "删除失败"
        })
    }
    loading.value = false
}

const newFormRef = ref<FormInstance>()
const newForm = reactive<Role>({
    id: '',
    name: '',
    level: '',
    createTime: '',
    menus: [],
    dataScope: '',
    depts: []
})

const updateFormRef = ref<FormInstance>()
const updateForm = reactive<Role>({
    id: '',
    name: '',
    level: '',
    createTime: '',
    menus: [],
    dataScope: '',
    depts: []
})

const newrules = reactive<FormRules<Role>>({
    name: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度应在3到20个字符之间', trigger: 'blur' },
    ],
    level: [
        { required: true },
    ],
    dataScope: [
        { required: true }
    ]

})

const updaterules = reactive<FormRules<Role>>({
    name: [
        { min: 3, max: 20, message: '长度应在3到20个字符之间', trigger: 'blur' },
    ],
})

const submitUpdateForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            loading.value = true
            updateForm.id = multipleSelection.value[0].id
            updateForm.name = updateForm.name || multipleSelection.value[0].name
            updateForm.level = updateForm.level || multipleSelection.value[0].level
            updateForm.dataScope = updateForm.dataScope || multipleSelection.value[0].dataScope
            updateForm.menus = multipleSelection.value[0].menus
            updateForm.createTime = multipleSelection.value[0].createTime
            const res = await updateRole(updateForm);
            if (res.status == '204') {
                ElNotification({
                    title: 'Success',
                    message: "修改成功",
                    type: 'success'
                })
                tableData[tableData.findIndex(x => x.id == updateForm.id)] = { ...updateForm }
                drawer_update.value = false
            }
        } else {
            console.log('error submit!', fields)
        }
        loading.value = false
    })
}

const resetUpdateForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const submitNewForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            loading.value = true
            updateForm.menus = []
            const res = await createRole(newForm);
            if (res.status == '201') {
                ElNotification({
                    title: "Success",
                    type: "success",
                    message: "添加成功"
                })
                drawer_new.value = false
                getByPage()
            } else {
                ElNotification({
                    type: "error",
                    title: "Error",
                    message: '添加失败' + res.data.message
                })
                loading.value = false
            }
        } else {
            console.log('error submit!', fields)
            loading.value = false
        }
    })
}

const resetNewForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}



// 列表管理Start
const pageSize = 7;
const totalSize = ref(1);
const currentPage = ref(1);
const loading = ref(false)
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<Role[]>([])
const toggleSelection = (rows?: Role[]) => {
    if (rows) {
        rows.forEach((row) => {
            multipleTableRef.value!.toggleRowSelection(row, undefined)
        })
    } else {
        multipleTableRef.value!.clearSelection()
    }

}

const handleRowChick = (row) => {
    const selected = multipleSelection.value.some((item) => item.id === row.id)
    if (!selected) {
        multipleSelection.value.push(row)
        multipleTableRef.value.toggleRowSelection(row, true)
    } else {
        const finArr = multipleSelection.value.filter((item) => {
            return item.id !== row.id
        })
        multipleSelection.value = finArr
        multipleTableRef.value.toggleRowSelection(row, false)
    }

}

const handleSelectionChange = (val: Role[]) => {
    multipleSelection.value = val
    handleMenuSelect()
}

const handleMenuSelect = () => {
    if (multipleSelection.value.length != 1) {
        treeRef.value.setCheckedKeys([], false);
    } else {
        const row = multipleSelection.value[0]

        let menuArray = []
        for (let i of row.menus) {
            menuArray.push(i.id)
        }
        treeRef.value.setCheckedKeys(menuArray, true);
    }

}

const tableData: Role[] = reactive([

])



const getByPage = async () => {
    let params = {
        page: currentPage.value - 1,
        size: pageSize
    }
    loading.value = true
    tableData.length = 0
    const res = await getRoleByPage(params)
    if (res != null) {
        if (res.status == '200') {
            console.log("获取成功，当前页码：", currentPage.value, "当前页面大小：", pageSize)
            const data = res.data
            totalSize.value = data.totalElements
            for (let i of data.content) {
                let role: Role = {
                    id: i.id,
                    name: i.name,
                    level: i.level,
                    createTime: i.createTime,
                    menus: [],
                    dataScope: i.dataScope,
                    depts: []
                }
                for (let menu of i.menus) {
                    role.menus.push({ id: menu.id })
                }
                tableData.push(role)
            }

        } else {
            console.log("获取失败，当前页码：", currentPage.value, "当前页面大小：", pageSize)
        }
    } else {
        console.log("请求失败")
    }
    nextTick(() => {
        loading.value = false
    })

}




//列表管理end


//菜单授权管理Start
const currentRole = ref('')
const loadingMenu = ref(false)
const treeRef = ref<InstanceType<typeof ElTree>>()
const defaultProps = {
    children: 'children',
    label: 'label',
}
const data = reactive([])

const save = async () => {
    const temp = multipleSelection.value[0]
    const menuArray = treeRef.value.getCheckedKeys()
    let params = {
        id: temp.id,
        level: temp.level,
        menus: [],
        name: temp.name,
        createTime: temp.createTime,
        dataScope: temp.dataScope
    }

    for (let i of menuArray) {
        params.menus.push({ id: i })
    }
    loading.value = true
    const res = await updateRoleMenu(params)
    if (res != null) {
        if (res.status == '204') {
            ElNotification({
                    title: "Success",
                    type: "success",
                    message: "保存成功"
                })
                getByPage()
        } else {
            ElNotification({
                    title: "Error",
                    type: "error",
                    message: "保存失败"+res.status
                })
                loading.value = false
        }
    } else {
        ElNotification({
                    title: "Error",
                    type: "error",
                    message: "请求错误"
                })
                loading.value = false
    }

}

const getAllMenu = async () => {
    loadingMenu.value = true
    const res = await getMenu()
    if (res != null) {
        if (res.status == '200') {
            for (let i of res.data) {
                if (i.children != null) {
                    let tempc = {
                        id: i.id,
                        label: i.meta.title,
                        children: []
                    }
                    for (let j of i.children) {
                        tempc.children.push({
                            id: j.id,
                            label: j.meta.title
                        })
                    }
                    data.push(tempc)
                } else {
                    data.push({
                        id: i.id,
                        label: i.name
                    })
                }

            }
        } else {
            console.log("xxxxxxxxxx获取失败xxxxxxxxx")
        }
    } else {
        console.log("请求失效")
    }
    loadingMenu.value = false
}


onBeforeMount(() => {
    getByPage()
    getAllMenu()
})

</script>

<style>
.el-row {
    margin-bottom: 20px;
}

.el-row:last-child {
    margin-bottom: 0;
}

.el-col {
    border-radius: 4px;
}

.grid-content {
    border-radius: 4px;
    min-height: 36px;
}

.example-pagination-block+.example-pagination-block {
    margin-top: 10px;
}

.example-pagination-block .example-demonstration {
    margin-bottom: 16px;
}
</style>
